package com.enjoy.xbase.db.impi;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.enjoy.xbase.db.annotation.AnnTableName;
import com.enjoy.xbase.db.handle.ISelect;
import com.enjoy.xbase.db.tools.DBTools;
import com.enjoy.xbase.db.tools.LogDb;

import java.util.ArrayList;
import java.util.List;

public class MSelect implements ISelect {
    private SQLiteDatabase db;
    private String[] columns;
    private String selection;
    private String[] selectionArgs;
    private String having;
    private String orderBy;
    private int start;
    private int icount;

    public MSelect(SQLiteDatabase db) {
        this.db = db;
    }

    @Override
    public ISelect selects(String... columns) {
        this.columns = columns;
        return this;
    }

    @Override
    public ISelect where(String selection, String... selectionArgs) {
        this.selection = selection;
        this.selectionArgs = selectionArgs;
        return this;
    }

    @Override
    public ISelect groupBy(String having) {
        this.having = having;
        return this;
    }

    @Override
    public ISelect order(String order) {
        this.orderBy = order;
        return this;
    }

    @Override
    public ISelect offset(int start) {
        this.start = start;
        return this;
    }

    @Override
    public ISelect limit(int icount) {
        this.icount = icount;
        return this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> List<T> finds(Class<T> modelClass) {
        if (this.db == null) {
            return null;
        }
        AnnTableName annotation = modelClass.getAnnotation(AnnTableName.class);
        String tbName;
        if (annotation != null) {
            tbName = annotation.value();
        } else {
            tbName = modelClass.getSimpleName().toLowerCase();
        }
        String litms = null;
        if (icount > 0) {
            litms = start + "," + icount;
        } else if (start > 0) {
            litms = "" + start;
        }
        Cursor cursor = db.query(tbName, columns, selection, selectionArgs, null, having, orderBy, litms);
        List<T> redatas = new ArrayList<>();
        if (cursor.moveToFirst()) {
            do {
                try {
                    redatas.add((T) DBTools.cursor2Obj(cursor, modelClass));
                } catch (Exception e) {
                    LogDb.err("数据库异常", "添加异常" + e.toString());
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return redatas;
    }

    @Override
    public <T> T find(Class<T> modelClass) {
        List<T> redatas = finds(modelClass);
        if (redatas != null && redatas.size() > 1) {
            throw new RuntimeException("查询结果数量大于1");
        } else if (redatas != null && redatas.size() == 1) {
            return redatas.get(0);
        } else {
            return null;
        }
    }
}
